package com.celan.year2023.month01.day28;

import java.util.ArrayList;

public class Solution {
    public int waysToMakeFair(int[] nums) {
        int s1 = 0, s2 = 0;
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            s1 += i % 2 == 0 ? nums[i] : 0;
            s2 += i % 2 == 1 ? nums[i] : 0;
        }
        int t1 = 0, t2 = 0;
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            int v = nums[i];
            ans += i % 2 == 0 && t2 + s1 - t1 - v == t1 + s2 - t2 ? 1 : 0;
            ans += i % 2 == 1 && t2 + s1 - t1 == t1 + s2 - t2 - v ? 1 : 0;
            t1 += i % 2 == 0 ? v : 0;
            t2 += i % 2 == 1 ? v : 0;
        }
        return ans;
    }

    public String countAndSay(int n) {
        String str = "1";
        for (int i = 2; i <= n; ++i) {
            StringBuilder sb = new StringBuilder();
            int start = 0;
            int pos = 0;
            while (pos < str.length()) {
                while (pos < str.length() && str.charAt(pos) == str.charAt(start)) {
                    pos++;
                }
                sb.append(Integer.toString(pos - start)).append(str.charAt(start));
                start = pos;
            }
            str = sb.toString();
        }
        return str;
    }

    public int firstMissingPositive(int[] nums) {
        int n = nums.length;
        boolean oneOccur = false;
        int res = 0, max = 0, min = 1;
        int[] dic = new int[n];
        for (int i = 0; i < n; i++) {
            if (nums[i] <= 0) continue;
            if (nums[i] == 1) oneOccur = true;
            max = Math.max(max, nums[i]);
            if (nums[i] <= n) dic[nums[i] - 1]++;
        }
        //没有出现1
        if (!oneOccur) return 1;
        //出现1,中间也连续
        //出现1,中间不连续
        for (int i = 1; i < n; i++) {
            if (dic[i] == 0) return i + 1;
        }
        return max + 1;
    }
    //[7,8,2,1,12] 7
    //[1,2,3,4,5]

    public double myPow(double x, int n) {
        if (n == 0) return 1;
        double res = 1, y = x;
        long multi = 1, cnt = n;
        if (n < 0) {
            x = 1 / x;
            cnt = -n;
        }
        while (cnt < 0) {
            while (cnt + multi <= 0) {
                res *= y;
                y *= y;
                cnt += multi;
                multi *= 2;
            }
            multi = 1;
            y = x;
        }
        return res;
    }

    public int mySqrt(int x) {
        if (x == 0) return 0;
        int res = 1;
        for (int i = 1; i < x; i++) {
            if (i * i == x) return i;
            if (i * i > x || i * i < 0 && (i - 1) * (i - 1) < x) return i - 1;
        }
        return res;
    }
}
